package com.foreknow.demo24;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 将从数据库查询到的数据以对象方式(Emp)保存到List集合
 */
public class Demo {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demodb?useUnicode=true&characterEncoding=utf8&useSSL=false","root","zjjlive82");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from emp");
            List<Emp> list = new ArrayList<>();
            while (resultSet.next()){
                int empno = resultSet.getInt("empno");
                String ename = resultSet.getString("ename");
                String job = resultSet.getString("job");
                //将以上信息封装到Emp对象中
                Emp emp = new Emp();
                emp.setEmpno(empno);
                emp.setEname(ename);
                emp.setJob(job);
                //要将当前对象保存到List集合中
                list.add(emp);
            }
            //遍历list集合
            for (Emp emp: list) {
                System.out.println(emp.getEmpno()+"---"+emp.getEname()+"---"+emp.getJob());
            }

            //关闭资源
            resultSet.close();
            statement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}